package com.jackchong.net

import com.jackchong.base.BaseView
import com.jackchong.ext.toastW
import io.reactivex.Observable

/**
 * author : jack(黄冲)
 * e-mail : 907755845@qq.com
 * create : 2020/7/29
 * desc   :
 */
class JNetParam<T, J: JBaseData<T>>(
    var view: BaseView,
    var dispatchMode: NetDispatchMode = NetDispatchMode.NORMAL,
    var loading: Loading,
    var networkChangeAutoRetry: Boolean = true,
    var cache: Cache,
    var onNext: ((T?) -> Unit),
    var onFail: ((J) -> Unit),
    var onError: ((cause: Throwable) -> Unit),
    var onComplete: (() -> Unit),
    var api: Observable<J>?) {
    companion object{
        inline fun <T, J: JBaseData<T>> build(block: Builder<T, J>.() -> Unit): JNetParam<T, J> {
            return Builder<T, J>().apply(block).build()
        }

        inline fun <T, J: JBaseData<T>> create(block: Builder<T, J>.() -> Unit): Builder<T, J> {
            return Builder<T, J>().apply(block)
        }
    }
}

class Builder<T, J: JBaseData<T>>{

    lateinit var view: BaseView

    var dispatchMode = NetDispatchMode.NORMAL

    var loadingMode = NetLoadingMode.DELAY

    var networkChangeAutoRetry = true

    var strategy = CacheStrategy.NOT()

    var onNext: ((T?) -> Unit) = { }

    var onFail: ((J) -> Unit) = {
        val msg = it.message() ?: ""
        val code = it.code() ?: ""
        toastW(msg)
    }

    var onError: ((cause: Throwable) -> Unit) = {
        val msg = it.message ?: ""
        toastW(msg)
    }

    var onComplete: (() -> Unit) = { }

    var api: Observable<J>? = null

    fun build(): JNetParam<T, J> {
        return JNetParam(view, dispatchMode, Loading.obtain(loadingMode, view), networkChangeAutoRetry, Cache.obtain(strategy, api?.hashCode()?: 0), onNext, onFail, onError, onComplete, api)
    }
}
